package com.naizhuai.Model.db.user;

import android.content.Context;
import android.support.annotation.NonNull;
import com.naizhuai.Model.db.AppDatabase;
import com.naizhuai.base.AppExecutors;

/**
 * @author：lichenxi
 * @date 2018/2/28 10
 * email：525603977@qq.com
 * Fighting
 */
public class LocalUserData implements UserDataSourse {
    private static volatile LocalUserData INSTANCE;

    private @NonNull
    UserDao mUserDao;

    private @NonNull AppExecutors mAppExecutors;

    public static LocalUserData getInstance() {
        if (INSTANCE == null) {
            synchronized (LocalUserData.class) {
                if (INSTANCE == null) {
                    INSTANCE = new LocalUserData();
                }
            }
        }
        return INSTANCE;
    }

    public LocalUserData() {
        mAppExecutors = new AppExecutors();
        mUserDao = AppDatabase.getInstance().UserDao();
    }

    @Override
    public PersonUserBean getUserSyn(String uid) {
       return mUserDao.searchUserByUid(uid);
    }

    @Override
    public void getUserAsyn(String uid, GetUserCallback callback) {
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                final PersonUserBean user= mUserDao.searchUserByUid(uid);
                mAppExecutors.mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        if (user!=null){
                            callback.onUserLoaded(user);
                        }else {
                            callback.onDataNotAvailable();
                        }
                    }
                });
            }
        };

        mAppExecutors.diskIO().execute(runnable);
    }

    @Override
    public void getUserByPhone(String phone, GetUserCallback callback) {
        mAppExecutors.diskIO().execute(new Runnable() {
            @Override
            public void run() {
                PersonUserBean user=mUserDao.searchUserByPhone(phone);
                mAppExecutors.mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        if (user!=null){
                            callback.onUserLoaded(user);
                        } else {
                            callback.onDataNotAvailable();
                        }
                    }
                });
            }
        });
    }

    @Override
    public void saveUser(PersonUserBean user) {
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
             mUserDao.saveUser(user);
            }
        };

        mAppExecutors.diskIO().execute(runnable);
    }

    @Override
    public void updateLoginUser(GetUserCallback callback) {

    }
}
